
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.viewsets import ModelViewSet

from apps.spits.models import Spit
from apps.spits.serializers import SpitSchema

from mongoengine import *

from apps.spits.pagination import PagNun

connect('test', host='localhost', port=27017)
# connect('test', host='47.114.168.253', port=27017)

class SpitViewSet(ModelViewSet):
    queryset = Spit.objects.all()
    serializer_class = SpitSchema
    pagination_class = PagNun


class SplitChildrenAPIView(APIView):
    def get(self,request,id):
        spit = Spit.objects.get(id=id)
        spits = Spit.objects.filter(parent=spit)
        serializer = SpitSchema(spits ,many=True)
        return Response(serializer.data)

class Spitupdatethumbup(APIView):
# 点赞或取消点赞
# /spit/{id}/updatethumbup/ PUT
    def put(self,request,id):
        spit = Spit.objects.get(id=id)
        if spit.hasthumbup:
            spit.thumbup -= 1
            spit.hasthumbup = False
        else:
            spit.thumbup += 1
            spit.hasthumbup = True
        spit.save()
        return Response({
            "message":'操作成功',
            "success":'True',
        })

class Spitcollect(APIView):
#  /spit/{id}/collect/ PUT
    def put(self,request,id):
        spit = Spit.objects.get(id=id)
        if spit.collected:
            spit.collected = False
        else:
            spit.collected = True
        spit.save()
        return Response({
            "message": '操作成功',
            "success": 'True',
        })